package com.crawler.controller;

import java.util.Map;

import com.core.plugin.bind.Route;
import com.crawler.clent.Crawler;
import com.crawler.clent.CrawlerManager;
import com.crawler.pojo.Constant;
import com.crawler.pojo.CrawlerSeed;
import com.crawler.pojo.Operate;
import com.google.common.collect.Maps;
import com.jfinal.core.Controller;
@Route(controllerKey="/crawler",viewPath="/pages/crawler")
public class CrawlerController extends Controller {
	
	public void fetch(){
		Map<String,Object> map = Maps.newHashMap();
		CrawlerSeed seed = new CrawlerSeed();
		seed.setUsername(getPara("username"));
		seed.setPassword(getPara("password"));
		seed.setCheckCode(getPara("checkCode"));
		seed.setOp(getOp(getPara("op")));
//		boolean isCrawling = breakCrawler(seed);//同一个账号不能同时抓取
		Crawler crawler = CrawlerManager.get(getPara("username"));
		map = crawler.start(seed);
		if(map == null){
			map = Maps.newHashMap();
			map.put(Constant.ERROR, getPara("username")+": isCrawling");
		}
		if(map.containsKey(Constant.OPERATE)){
			map.put(Constant.FLAG,true);
			renderJson(map);
			return;
		}
		if(map.containsKey(Constant.ERROR)){
			map.put(Constant.FLAG,false);
			renderJson(map);
			return;
		}
		map.put(Constant.FLAG,true);
		renderJson(map);
		saveToDb(map);
	}

	@SuppressWarnings("unused")
	private boolean breakCrawler(CrawlerSeed seed) {
		if(seed.getOp().equals(Operate.login) && CrawlerManager.isCrawling(seed.getUsername()))
			return true;
		return false;
	}

	private Operate getOp(String op) {
		for (Operate operate : Operate.values()) {
			if (operate.getValue().equals(op)) {
				return operate;
			}
		}
		return null;
	}

	private void saveToDb(Map<String, Object> map) {
		
	}

}
